package com.joker.aigc.tools.service.video.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joker.aigc.tools.domian.dto.VideoDetailDTO;
import com.joker.aigc.tools.domian.dto.VideoListDTO;
import com.joker.aigc.tools.domian.dto.VideoUploadRequestDTO;
import com.joker.aigc.tools.domian.po.ActorMappingsPO;
import com.joker.aigc.tools.domian.po.VideoCategoryMappingsPO;
import com.joker.aigc.tools.domian.po.VideosPO;
import com.joker.aigc.tools.mapper.ActorMappingsMapper;
import com.joker.aigc.tools.mapper.VideoCategoryMappingsMapper;
import com.joker.aigc.tools.mapper.VideosMapper;
import com.joker.aigc.tools.service.video.MinioService;
import com.joker.aigc.tools.service.video.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 视频服务实现类
 *
 * @author system
 * @date 2023-12-01
 */
@Slf4j
@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideosMapper videosMapper;

    @Autowired
    private VideoCategoryMappingsMapper videoCategoryMappingsMapper;

    @Autowired
    private ActorMappingsMapper actorMappingsMapper;

    @Autowired
    private MinioService minioService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long uploadVideo(File videoFile, MultipartFile thumbnailFile, VideoUploadRequestDTO request) {
        try {
            // 1. 上传视频文件
            String videoUrl = minioService.uploadVideo(videoFile);

            // 2. 上传缩略图（如果有）
            String thumbnailUrl = null;
            if (thumbnailFile != null && !thumbnailFile.isEmpty()) {
                thumbnailUrl = minioService.uploadThumbnail(thumbnailFile);
            }

            // 3. 保存视频信息
            VideosPO video = new VideosPO();
            video.setActorId(request.getActorId());
            video.setTitle(request.getTitle());
            video.setDescription(request.getDescription());
            video.setDuration(request.getDuration());
            video.setReleaseDate(LocalDate.now());
            video.setFilePath(videoUrl);
            video.setThumbnailPath(thumbnailUrl);
            video.setCreatedAt(LocalDateTime.now());
            video.setUpdatedAt(LocalDateTime.now());

            videosMapper.insert(video);
            Long videoId = video.getId();

            // 4. 保存分类映射关系
            if (request.getCategoryIds() != null) {
                for (Long categoryId : request.getCategoryIds()) {
                    VideoCategoryMappingsPO mapping = new VideoCategoryMappingsPO();
                    mapping.setVideoId(videoId);
                    mapping.setCategoryType(1); // 主分类
                    mapping.setCategoryId(categoryId);
                    videoCategoryMappingsMapper.insert(mapping);
                }
            }

            // 5. 保存子分类映射关系
            if (request.getSubCategoryIds() != null) {
                for (Long subCategoryId : request.getSubCategoryIds()) {
                    VideoCategoryMappingsPO mapping = new VideoCategoryMappingsPO();
                    mapping.setVideoId(videoId);
                    mapping.setCategoryType(1); // 子分类也是类型分类
                    mapping.setSubCategoryId(subCategoryId);
                    videoCategoryMappingsMapper.insert(mapping);
                }
            }

            // 6. 保存演员映射关系
            ActorMappingsPO actorMapping = new ActorMappingsPO();
            actorMapping.setVideoId(videoId);
            actorMapping.setActorId(request.getActorId());
            actorMapping.setRole("发布者");
            actorMapping.setCreatedAt(LocalDateTime.now());
            actorMappingsMapper.insert(actorMapping);

            return videoId;
        } catch (Exception e) {
            log.error("上传视频失败: {}", e.getMessage(), e);
            throw new RuntimeException("上传视频失败: " + e.getMessage());
        }
    }

    @Override
    public VideoDetailDTO getVideoDetail(Long videoId, Long userId) {
        try {
            VideoDetailDTO detail = videosMapper.getVideoDetailById(videoId);
            if (detail == null) {
                throw new RuntimeException("视频不存在");
            }

            // TODO: 根据userId获取用户相关数据（收藏、观看进度等）
            // 这里先返回默认值
            VideoDetailDTO.UserDataDTO userData = new VideoDetailDTO.UserDataDTO();
            userData.setIsFavorite(false);
            userData.setWatchProgress(0);
            userData.setLastWatched(null);
            detail.setUserData(userData);

            return detail;
        } catch (Exception e) {
            log.error("获取视频详情失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取视频详情失败: " + e.getMessage());
        }
    }

    @Override
    public List<VideoListDTO> getVideoList(Long categoryId, Long subCategoryId, Integer page, Integer size) {
        try {
            Page<VideoListDTO> pageParam = new Page<>(page, size);
            return videosMapper.getVideoList(pageParam, categoryId, subCategoryId).getRecords();
        } catch (Exception e) {
            log.error("获取视频列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取视频列表失败: " + e.getMessage());
        }
    }

    @Override
    public List<VideoListDTO> searchVideos(String keyword, Integer page, Integer size) {
        try {
            Page<VideoListDTO> pageParam = new Page<>(page, size);
            return videosMapper.searchVideos(pageParam, keyword).getRecords();
        } catch (Exception e) {
            log.error("搜索视频失败: {}", e.getMessage(), e);
            throw new RuntimeException("搜索视频失败: " + e.getMessage());
        }
    }

    @Override
    public String getVideoStreamUrl(Long videoId) {
        try {
            QueryWrapper<VideosPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", videoId);
            VideosPO video = videosMapper.selectOne(queryWrapper);

            if (video == null) {
                throw new RuntimeException("视频不存在");
            }

            return video.getFilePath();
        } catch (Exception e) {
            log.error("获取视频流URL失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取视频流URL失败: " + e.getMessage());
        }
    }
} 